package com.obas.view.explorer {
   import com.ease.core.events.ViewOperationEvent;
   import com.ease.framework.CommandCompletionEvent;
   import com.obas.component.tree.treeclass.Node;
   import com.obas.constants.TestingLibConstants;
   import com.obas.event.DataRefreshEvent;
   import com.obas.event.ItestOperationEvent;
   import com.obas.flex.common.util.ListDataUtil;
   import com.obas.flex.common.util.ResourceUtil;
   import com.obas.model.business.SystemFunction;
   import com.obas.model.business.SystemProject;
   import com.obas.model.business.SystemScenario;
   import com.obas.model.business.SystemUsecase;
   import com.obas.model.business.TestcaseScript;
   import com.obas.project.view.ProjectNewView;
   import com.obas.view.feature.CreateFunctionDialog;
   import com.obas.view.menu.CaseMenu;
   import com.obas.view.menu.FunctionMenu;
   import com.obas.view.menu.ProjectEmptyMenu;
   import com.obas.view.menu.ProjectMenu;
   import com.obas.view.menu.ScenarioMenu;
   import com.obas.view.scenario.CreateSenarioDialog;
   import com.obas.view.script.CreateTestScriptDialog;
   import com.obas.view.testcase.CreateTestCaseDialog;
   import com.ease.component.managers.ConfirmHelper;
   import com.ease.component.managers.ErrorManager;

   import flash.events.ContextMenuEvent;
   import flash.events.EventDispatcher;

   import mx.collections.ArrayCollection;
   import mx.controls.Alert;
   import mx.events.CloseEvent;
   import mx.events.ListEvent;
   import mx.managers.PopUpManager;

   [Event(name="{com.ease.core.events.ViewOperationEvent.REQUEST_ID}", type="com.ease.core.events.ViewOperationEvent")]
   [Event(name="{com.obas.event.ItestOperationEvent.REQUEST_ID}", type="com.obas.event.ItestOperationEvent")]
   public class ITestExplorerViewMediator extends EventDispatcher {
      private var listUtil:ListDataUtil = new ListDataUtil(keyFunction);

      public var _view:ITestExplorerView;

      [InjectableView]
      public function get view():ITestExplorerView {
         return _view;
      }

      public function set view(value:ITestExplorerView):void {
         _view = value;
         init();
      }

      private function init():void {
         view.addEventListener(ProjectEmptyMenu.CREATE_PROJECT, onCreateProject);
         view.addEventListener(ProjectMenu.DELETE_PROJECT, onDeleteProject);
         view.addEventListener(ProjectMenu.MODIFY_PROJECT, onModifyProject);

         view.addEventListener(ProjectMenu.CREATE_SCENARIO, onCreateScenario);
         view.addEventListener(ScenarioMenu.MODIFY_SCENARIO, onModifyScenario);
         view.addEventListener(ScenarioMenu.DELETE_SCENARIO, onDeleteScenario);

         view.addEventListener(ScenarioMenu.CREATE_CASE, onCreateCase);
         view.addEventListener(CaseMenu.MODIFY_CASE, onModifyCase);
         view.addEventListener(CaseMenu.DELETE_CASE, onDeleteCase);

         view.addEventListener(CaseMenu.CREATE_FUNCTION, onCreateFunction);
         view.addEventListener(FunctionMenu.MODIFY_FUNCTION, onModifyFunction);
         view.addEventListener(FunctionMenu.DELETE_FUNCTION, onDeleteFunction);

         view.addEventListener(FunctionMenu.CREATE_SCRIPT, onCreateScript);

         view.navTree.addEventListener(ListEvent.ITEM_DOUBLE_CLICK, onDoubleClick);

         dispatchEvent(new ItestOperationEvent(null));
         //增加右键菜单
         /*
         var projectContextMenu:ContextMenu = new ContextMenu();
         var newProjectContextMenuItem:ContextMenuItem = new ContextMenuItem("新建项目");
         projectContextMenu.customItems.push(newProjectContextMenuItem);
         newProjectContextMenuItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, newProject);
         this._view.contextMenu = projectContextMenu;
         */
      }

      private function newProject(evt:ContextMenuEvent):void {
         var dialog:ProjectNewView = PopUpManager.createPopUp(view.root, ProjectNewView, true) as ProjectNewView;
         PopUpManager.centerPopUp(dialog);
      }

      private function keyFunction(item:*):String {
         return item.entity.id + "";
      }

      [ResponseHandler("{com.obas.event.ItestOperationEvent.RETURN_ID}")]
      public function onItestOperationEvent(event:CommandCompletionEvent):void {
         if (event.error) {
            ErrorManager.showErrorMessage(ResourceUtil.getErrorString("", event.error));
            return ;
         }

         var request:ItestOperationEvent = event.request as ItestOperationEvent;
         if (request.actionType == ItestOperationEvent.GET_PROJECT) {
            var results:ArrayCollection = event.result as ArrayCollection;
            for each (var project:SystemProject in results) {
               var childNode:Node = view.navTree.nodeFactory.createNode(project);
               childNode.type = TestingLibConstants.ITEMTYPE_PROJECT;
               view.treeNodes.addItem(childNode);
            }
         }
         else if (request.actionType == ItestOperationEvent.DELETE_CASE ||
                     request.actionType == ItestOperationEvent.DELETE_FUNCTION ||
                     request.actionType == ItestOperationEvent.DELETE_PROJECT ||
                     request.actionType == ItestOperationEvent.DELETE_SCENARIO||
                     request.actionType == ItestOperationEvent.DELETE_SCRIPT) {
            var node:Node = request.spec[1];
            var parentNode:Node = node.parentNode;
            if (parentNode) {
               parentNode.children.removeItemAt(parentNode.children.getItemIndex(node));
               parentNode.children.refresh();
            }
            else {
               view.treeNodes.removeItemAt(view.treeNodes.getItemIndex(node));
            }
            view.navTree.invalidateDisplayList();
         }
      }

      private function onCreateScenario(e:*):void {
         var dialog:CreateSenarioDialog = PopUpManager.createPopUp(view.root, CreateSenarioDialog, true) as CreateSenarioDialog;
         dialog.parentProject = view.navTree.selectedItem as Node;
         PopUpManager.centerPopUp(dialog);
      }

      private function onModifyScenario(e:*):void {
         var dialog:CreateSenarioDialog = PopUpManager.createPopUp(view.root, CreateSenarioDialog, true) as CreateSenarioDialog;
         var sltNode:Node = view.navTree.selectedItem as Node;
         dialog.sceName.text = sltNode.name;
         dialog.actionType = TestingLibConstants.ACTION_UPDATE;
         dialog.systemScenario = sltNode.entity as SystemScenario;
//         dialog.parentProject = view.navTree.selectedItem as Node;
         PopUpManager.centerPopUp(dialog);
      }

      private function onModifyProject(e:*):void {
         var dialog:ProjectNewView = PopUpManager.createPopUp(view.root, ProjectNewView, true) as ProjectNewView;
         var sltNode:Node = view.navTree.selectedItem as Node;
         dialog.projectName.text = sltNode.name;
         dialog.actionType = TestingLibConstants.ACTION_UPDATE;
         dialog.systemProject = sltNode.entity as SystemProject;
         PopUpManager.centerPopUp(dialog);
      }

      private function onCreateProject(e:*):void {
         var dialog:ProjectNewView = PopUpManager.createPopUp(view.root, ProjectNewView, true) as ProjectNewView;
         dialog.actionType = TestingLibConstants.ACTION_CREATE;
         PopUpManager.centerPopUp(dialog);
      }

      private function onDeleteProject(e:*):void {
         ConfirmHelper.showConfirmDialog("删除", "确定要删除该测试项目吗？", onDeleteProjectClose);
      }

      private function onDeleteProjectClose(evt:CloseEvent):void {
         if (evt.detail == Alert.YES) {
            dispatchEvent(new ItestOperationEvent([view.navTree.selectedItem.entity, view.navTree.selectedItem], ItestOperationEvent.DELETE_PROJECT));
         }
      }

      private function onCreateCase(e:*):void {
         var dialog:CreateTestCaseDialog = PopUpManager.createPopUp(view.root, CreateTestCaseDialog, true) as CreateTestCaseDialog;
         dialog.parentProject = view.navTree.selectedItem as Node;
         PopUpManager.centerPopUp(dialog);
      }

      private function onModifyFunction(e:*):void {
         var dialog:CreateFunctionDialog = PopUpManager.createPopUp(view.root, CreateFunctionDialog, true) as CreateFunctionDialog;
         var sltNode:Node = view.navTree.selectedItem as Node;
         dialog.nameInput.text = sltNode.name;
//         dialog.parentProject = view.navTree.selectedItem as Node;
         dialog.actionType = TestingLibConstants.ACTION_UPDATE;
         dialog.systemFunction = sltNode.entity as SystemFunction;
         PopUpManager.centerPopUp(dialog);
      }

      private function onModifyCase(e:*):void {
         var dialog:CreateTestCaseDialog = PopUpManager.createPopUp(view.root, CreateTestCaseDialog, true) as CreateTestCaseDialog;
         var sltNode:Node = view.navTree.selectedItem as Node;
         dialog.nameInput.text = sltNode.name;
//         dialog.parentProject = view.navTree.selectedItem as Node;
         dialog.actionType = TestingLibConstants.ACTION_UPDATE;
         dialog.systemUsecase = sltNode.entity as SystemUsecase;
         PopUpManager.centerPopUp(dialog);
      }

      private function onDeleteScenario(e:*):void {
         ConfirmHelper.showConfirmDialog("删除", "确定要删除该测试场景吗？", onDeleteScenarioClose);
      }

      private function onDeleteScenarioClose(evt:CloseEvent):void {
         if (evt.detail == Alert.YES) {
            dispatchEvent(new ItestOperationEvent([view.navTree.selectedItem.entity, view.navTree.selectedItem], ItestOperationEvent.DELETE_SCENARIO));
         }
      }

      private function onCreateFunction(e:*):void {
         var dialog:CreateFunctionDialog = PopUpManager.createPopUp(view.root, CreateFunctionDialog, true) as CreateFunctionDialog;
         dialog.parentProject = view.navTree.selectedItem as Node;
         PopUpManager.centerPopUp(dialog);
      }

      private function onDeleteCase(e:*):void {
         ConfirmHelper.showConfirmDialog("删除", "确定要删除该测试用例吗？", onDeleteCaseClose);
      }

      private function onDeleteCaseClose(evt:CloseEvent):void {
         if (evt.detail == Alert.YES) {
            dispatchEvent(new ItestOperationEvent([view.navTree.selectedItem.entity, view.navTree.selectedItem], ItestOperationEvent.DELETE_CASE));
         }
      }

      private function onCreateScript(e:*):void {
         var dialog:CreateTestScriptDialog = PopUpManager.createPopUp(view.root, CreateTestScriptDialog, true) as CreateTestScriptDialog;
         dialog.parentProject = view.navTree.selectedItem as Node;
         PopUpManager.centerPopUp(dialog);
      }

      private function onDeleteFunction(e:*):void {
         ConfirmHelper.showConfirmDialog("删除", "确定要删除该测试功能点吗？", onDeleteFunctionClose);
      }

      private function onDeleteFunctionClose(evt:CloseEvent):void {
         if (evt.detail == Alert.YES) {
            dispatchEvent(new ItestOperationEvent([view.navTree.selectedItem.entity, view.navTree.selectedItem], ItestOperationEvent.DELETE_FUNCTION));
         }
      }

      private function onDoubleClick(e:*):void {
         var selectedNode:Node = view.navTree.selectedItem as Node;
         if (selectedNode.type == TestingLibConstants.ITEMTYPE_SCRIPT) {
            var param:Object = new Object();
            param.targetView = "commonView";
            param.className = "com.obas.view.script.ScriptEditView";
            param.createNew = "true";
            param.autoOpen = "true";
            param.entity = selectedNode.entity;
            dispatchEvent(new ViewOperationEvent([param.targetView], param));
         } else {
            var paramOther:Object = new Object();
            paramOther.targetView = "commonView";
            paramOther.className = "com.obas.view.EntityView";
            paramOther.createNew = "true";
            paramOther.autoOpen = "true";
            paramOther.model = selectedNode.entity;
            dispatchEvent(new ViewOperationEvent([paramOther.targetView], paramOther));
         }
      }

      [EventHandler("{com.obas.event.DataRefreshEvent.REQUEST_ID}")]
      public function onDataRefreshEvent(event:DataRefreshEvent):void {
         switch (event.actionType) {
            case DataRefreshEvent.TYPE_DELETE :
               deleteItems(event.spec.data);
               break;
            case DataRefreshEvent.TYPE_ADD_UPDATE :
               var parentNode:Node = event.spec.context;
               var datas:ArrayCollection = event.spec.data;
               if (datas && datas.length > 0) {
                  var item:* = datas.getItemAt(0);
                  var nodeType:String = getNodeType(item);
                  if(nodeType == "") {
                     return;
                  }
                  var childNode:Node = view.navTree.nodeFactory.createNode(item);
                  childNode.type = nodeType;
                  if (nodeType == TestingLibConstants.ITEMTYPE_SCRIPT) {
                     childNode.children = null;
                  }
                  var nodes:Array = [childNode];
                  if (parentNode) {
                     childNode.parentNode = parentNode;
                     listUtil.addOrUpdateItems(parentNode.children.source, nodes, true);
                     parentNode.children.refresh();
                  }
                  else {
                     listUtil.addOrUpdateItems(view.treeNodes.source, nodes, true);
                     view.treeNodes.refresh();
                  }
                  view.navTree.invalidateDisplayList();
               }

               break;
         }
      }

      private function deleteItems(items:ArrayCollection):void {
      }

      public function getNodeType(item:*):String {
         if (item is SystemProject) {
            return TestingLibConstants.ITEMTYPE_PROJECT;
         }
         else if (item is SystemScenario) {
            return TestingLibConstants.ITEMTYPE_SCENARIO;
         }
         else if (item is SystemUsecase) {
            return TestingLibConstants.ITEMTYPE_CASE;
         }
         else if (item is SystemFunction) {
            return TestingLibConstants.ITEMTYPE_FUNCTION;
         }
         else if (item is TestcaseScript) {
            return TestingLibConstants.ITEMTYPE_SCRIPT;
         }
         return "";
      }

   }
}